package com.example.common.base

import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.reflect.KClass

class Debouncer {
    private val timestamps = mutableMapOf<KClass<*>, Long>()
    private val mutex = Mutex()

    /**
     * 判断是否允许执行
     * @param key 唯一标识，一般是 Intent 的 KClass
     * @param debounceMillis 防抖时间
     */
    suspend fun shouldRun(key: KClass<*>, debounceMillis: Long): Boolean {
        mutex.withLock {
            val now = System.currentTimeMillis()
            val last = timestamps[key] ?: 0
            return if (now - last >= debounceMillis) {
                timestamps[key] = now
                true
            } else {
                false
            }
        }
    }
}